package com.enqualcomm.kids.activities;

import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;

import com.enqualcomm.kids.R;
import com.enqualcomm.kids.base.BaseActivity;
import com.isseiaoki.simplecropview.CropImageView;
import com.isseiaoki.simplecropview.callback.CropCallback;
import com.isseiaoki.simplecropview.callback.LoadCallback;
import com.isseiaoki.simplecropview.callback.SaveCallback;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.ViewById;

import java.io.File;

import common.utils.PromptUtil;

/**
 * Created by Administrator on 2016/6/24.
 */
@EActivity(R.layout.activity_crop_image)
public class CropImageActivity extends BaseActivity {

    @ViewById(R.id.cropImageView)
    CropImageView cropImageView;

    @AfterViews
    void setupView() {
        Intent intent = getIntent();
        Uri sourceUri = intent.getData();
        initView();
        showProgress();
        cropImageView.startLoad(sourceUri, new LoadCallback() {
            @Override
            public void onSuccess() {
                hideProgress();
            }

            @Override
            public void onError() {
                hideProgress();
                PromptUtil.longToast(CropImageActivity.this, "剪切图片加载失败");
            }
        });
    }

    private void initView() {
        cropImageView.setOutputWidth(160);
        cropImageView.setOutputHeight(160);
        cropImageView.setInitialFrameScale(0.5f);
        cropImageView.setCompressFormat(Bitmap.CompressFormat.PNG);
    }

    @Click(R.id.buttonDone)
    void startCropImage() {
        cropImageView.startCrop(createSaveUri(), mCropCallback, mSaveCallback);
    }

    public Uri createSaveUri() {
        return Uri.fromFile(new File(getCacheDir(), "cropped"));
    }

    private final CropCallback mCropCallback = new CropCallback() {
        @Override
        public void onSuccess(Bitmap cropped) {
            Intent intent = new Intent();
            intent.putExtra("data",cropped);
            setResult(RESULT_OK, intent);
            finish();
        }

        @Override
        public void onError() {
        }
    };

    private final SaveCallback mSaveCallback = new SaveCallback() {
        @Override
        public void onSuccess(Uri outputUri) {
        }

        @Override
        public void onError() {
            PromptUtil.longToast(CropImageActivity.this, "剪切图片失败");
        }
    };

    @Click(R.id.buttoncancel)
    void finishActivity(){
        Intent intent = new Intent();
        setResult(RESULT_CANCELED, intent);
        finish();
    }
}
